package com.suxin.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Classname BIOServer
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2020/12/25 22:43
 * @Created by ASUS
 */
public class BIOServer {

    public static void main(String[] args) throws Exception {

        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8888);

        while (true) {
            System.out.println("线程" + Thread.currentThread().getId() + "等待连接...");
            // 产生阻塞
            Socket accept = serverSocket.accept();
            System.out.println( "有客户端进来了..." );
            // 处理socket
            executorService.execute(() -> {
                handlerSocket(accept);
            });
        }
    }

    private static void handlerSocket(Socket accept) {
        byte[] bt = new byte[1024];
        InputStream inputStream = null;
        try {
            inputStream = accept.getInputStream();
            while (true) {
                System.out.println("线程" +Thread.currentThread().getId() + "等待read...");
                // 产生阻塞
                int read = inputStream.read(bt);
                System.out.println("线程" +Thread.currentThread().getId() + "接收到的数据为:--->" + new String(bt));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}